import React, { forwardRef, useState } from "react";
import styled from "@emotion/styled";
import { FiEye, FiEyeOff, FiAlertCircle } from "react-icons/fi";
import { duration, easing, spacing } from "../utils/design-tokens";

// 输入框尺寸类型
type InputSize = "small" | "medium" | "large";
// 输入框变体类型
type InputVariant = "default" | "filled" | "bordered" | "flushed";

// 输入框容器
const InputWrapper = styled.div<{
  $size: InputSize;
  $hasError?: boolean;
  $disabled?: boolean;
}>`
  position: relative;
  width: 100%;

  ${({ $disabled }) =>
    $disabled &&
    `
    opacity: 0.6;
    pointer-events: none;
  `}
`;

// 输入框主体
const InputElement = styled.input<{
  $variant: InputVariant;
  $size: InputSize;
  $hasError?: boolean;
  $hasIcon?: boolean;
  $hasRightElement?: boolean;
}>`
  width: 100%;
  border-radius: 6px;
  transition: border-color ${duration.fast}ms ${easing.ease},
    background-color ${duration.fast}ms ${easing.ease};
  font-family: inherit;
  outline: none;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  -webkit-appearance: none;
  appearance: none;

  // 尺寸样式
  ${({ $size }) => {
    switch ($size) {
      case "small":
        return `
          padding: ${spacing["2"]} ${spacing["3"]};
          font-size: 0.875rem;
          min-height: 2rem;
          
          @media (max-width: 768px) {
            font-size: 15px;
            min-height: 36px;
          }
        `;
      case "large":
        return `
          padding: ${spacing["3"]} ${spacing["4"]};
          font-size: 1.125rem;
          min-height: 3rem;
          
          @media (max-width: 768px) {
            font-size: 16px;
            min-height: 44px;
          }
        `;
      default: // medium
        return `
          padding: ${spacing["2"]} ${spacing["3"]};
          font-size: 0.95rem;
          min-height: 2.5rem;
          
          @media (max-width: 768px) {
            font-size: 15px;
            min-height: 40px;
          }
        `;
    }
  }}

  // 左侧图标间距
  ${({ $hasIcon, $size }) =>
    $hasIcon &&
    `
    padding-left: ${
      $size === "small" ? "2.25rem" : $size === "large" ? "3rem" : "2.5rem"
    };
  `}

  // 右侧元素间距
  ${({ $hasRightElement, $size }) =>
    $hasRightElement &&
    `
    padding-right: ${
      $size === "small" ? "2.25rem" : $size === "large" ? "3rem" : "2.5rem"
    };
  `}

  // 变体样式
  ${({ $variant, $hasError }) => {
    const borderColor = $hasError
      ? "var(--error-color)"
      : "var(--border-color)";
    const focusBorderColor = $hasError
      ? "var(--error-color)"
      : "var(--accent-color)";

    switch ($variant) {
      case "filled":
        return `
          background-color: var(--bg-secondary);
          border: 1px solid transparent;
          
          &:focus {
            background-color: var(--bg-primary);
            border-color: ${focusBorderColor};
          }
          
          &:hover:not(:focus) {
            background-color: var(--bg-tertiary);
          }
        `;
      case "bordered":
        return `
          background-color: transparent;
          border: 1px solid ${borderColor};
          
          &:focus {
            border-color: ${focusBorderColor};
          }
          
          &:hover:not(:focus) {
            border-color: var(--text-secondary);
          }
        `;
      case "flushed":
        return `
          background-color: transparent;
          border: none;
          border-bottom: 1px solid ${borderColor};
          border-radius: 0;
          padding-left: 0;
          padding-right: 0;
          
          &:focus {
            border-bottom-color: ${focusBorderColor};
          }
        `;
      default: // default
        return `
          background-color: var(--bg-primary);
          border: 1px solid ${borderColor};
          
          &:focus {
            border-color: ${focusBorderColor};
          }
          
          &:hover:not(:focus) {
            border-color: var(--text-secondary);
          }
        `;
    }
  }}

  &::placeholder {
    color: var(--text-tertiary);
  }

  &:disabled {
    cursor: not-allowed;
    background-color: var(--bg-secondary);
    color: var(--text-tertiary);
  }
`;

// 图标容器
const IconWrapper = styled.div<{
  $position: "left" | "right";
  $size: InputSize;
  $clickable?: boolean;
}>`
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  pointer-events: ${({ $clickable }) => ($clickable ? "auto" : "none")};
  cursor: ${({ $clickable }) => ($clickable ? "pointer" : "default")};
  transition: color ${duration.fast}ms ${easing.ease};

  ${({ $position, $size }) => {
    const spacingValue =
      $size === "small"
        ? spacing["3"]
        : $size === "large"
        ? spacing["4"]
        : spacing["3"];
    return $position === "left"
      ? `left: ${spacingValue};`
      : `right: ${spacingValue};`;
  }}

  &:hover {
    color: ${({ $clickable }) =>
      $clickable ? "var(--text-primary)" : "var(--text-secondary)"};
  }
`;

// 标签样式
const Label = styled.label<{ $required?: boolean; $hasError?: boolean }>`
  display: block;
  margin-bottom: ${spacing["2"]};
  font-size: 0.875rem;
  font-weight: 500;
  color: ${({ $hasError }) =>
    $hasError ? "var(--error-color)" : "var(--text-primary)"};

  ${({ $required }) =>
    $required &&
    `
    &::after {
      content: ' *';
      color: var(--error-color);
    }
  `}
`;

// 帮助文本
const HelperText = styled.div<{ $hasError?: boolean }>`
  margin-top: ${spacing["2"]};
  font-size: 0.75rem;
  color: ${({ $hasError }) =>
    $hasError ? "var(--error-color)" : "var(--text-secondary)"};
  display: flex;
  align-items: center;
  gap: ${spacing["1"]};
  line-height: 1.4;
`;

// 输入框属性接口
export interface InputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "size"> {
  variant?: InputVariant;
  size?: InputSize;
  label?: string;
  helperText?: string;
  errorMessage?: string;
  leftIcon?: React.ReactNode;
  rightElement?: React.ReactNode;
  isRequired?: boolean;
  isInvalid?: boolean;
  autoComplete?: string;
}

// 输入框组件
export const Input = forwardRef<HTMLInputElement, InputProps>(
  (
    {
      variant = "default",
      size = "medium",
      label,
      helperText,
      errorMessage,
      leftIcon,
      rightElement,
      isRequired = false,
      isInvalid = false,
      type = "text",
      disabled = false,
      className,
      autoComplete,
      name,
      ...props
    },
    ref
  ) => {
    const [showPassword, setShowPassword] = useState(false);
    const hasError = isInvalid || !!errorMessage;
    const isPassword = type === "password";
    const inputType = isPassword && showPassword ? "text" : type;

    // 自动推断 autocomplete 值（如果未提供）
    const getAutoComplete = (): string => {
      if (autoComplete !== undefined) return autoComplete;

      // 根据类型和 name 推断
      if (isPassword) {
        if (
          name?.toLowerCase().includes("new") ||
          name?.toLowerCase().includes("confirm")
        ) {
          return "new-password";
        }
        return "current-password";
      }

      if (type === "email") return "email";
      if (type === "tel") return "tel";
      if (type === "url") return "url";

      // 根据 name 推断
      if (name) {
        const lowerName = name.toLowerCase();
        if (lowerName.includes("username")) return "username";
        if (lowerName.includes("email")) return "email";
        if (lowerName.includes("phone") || lowerName.includes("tel"))
          return "tel";
        if (lowerName.includes("address")) return "street-address";
        if (lowerName.includes("city")) return "address-level2";
        if (lowerName.includes("country")) return "country-name";
        if (lowerName.includes("postal") || lowerName.includes("zip"))
          return "postal-code";
        if (lowerName.includes("firstname") || lowerName.includes("first-name"))
          return "given-name";
        if (lowerName.includes("lastname") || lowerName.includes("last-name"))
          return "family-name";
      }

      return "off";
    };

    const handleTogglePassword = (e: React.MouseEvent) => {
      e.stopPropagation();
      setShowPassword(!showPassword);
    };

    // 阻止点击输入框容器时的事件冒泡
    const handleWrapperClick = (e: React.MouseEvent) => {
      e.stopPropagation();
    };

    return (
      <div className={className} onClick={handleWrapperClick}>
        {label && (
          <Label $required={isRequired} $hasError={hasError}>
            {label}
          </Label>
        )}

        <InputWrapper $size={size} $hasError={hasError} $disabled={disabled}>
          {leftIcon && (
            <IconWrapper $position="left" $size={size}>
              {leftIcon}
            </IconWrapper>
          )}

          <InputElement
            ref={ref}
            type={inputType}
            $variant={variant}
            $size={size}
            $hasError={hasError}
            $hasIcon={!!leftIcon}
            $hasRightElement={!!rightElement || isPassword}
            disabled={disabled}
            name={name}
            autoComplete={getAutoComplete()}
            {...props}
          />

          {isPassword && (
            <IconWrapper
              $position="right"
              $size={size}
              $clickable
              onClick={handleTogglePassword}
            >
              {showPassword ? <FiEyeOff size={16} /> : <FiEye size={16} />}
            </IconWrapper>
          )}

          {rightElement && !isPassword && (
            <IconWrapper $position="right" $size={size}>
              {rightElement}
            </IconWrapper>
          )}
        </InputWrapper>

        {(errorMessage || helperText) && (
          <HelperText $hasError={hasError}>
            {hasError && <FiAlertCircle size={12} />}
            {errorMessage || helperText}
          </HelperText>
        )}
      </div>
    );
  }
);

Input.displayName = "Input";

export default Input;
